/*
 * Copyright 2008-2010 GP Software
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 * AbstractFileGenerator.java | Created on Jul 19, 2010
 */
package org.gp.fileGenerator;

import freemarker.template.Configuration;
import freemarker.template.ObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * Abstract class for the file generator
 *
 * @author Paul Augustine C. Mendoza
 */
public abstract class AbstractFileGenerator<T> implements FileGenerator {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private String template;
    private String templateRootPath;
    private Configuration config;
    private Map<String, T> root;

    public AbstractFileGenerator(String templateRootPath, String template) {
        this.root = new HashMap<String, T>();
        this.templateRootPath = templateRootPath;
        this.template = template;
        initialize();
    }

    private void initialize() {
        this.config = new Configuration();
        try {
            config.setDirectoryForTemplateLoading(
                    new File(templateRootPath));
            config.setObjectWrapper(ObjectWrapper.BEANS_WRAPPER);
        } catch (IOException e) {
            logger.error("Error in initializing.", e);
        }
    }

    protected Writer generateOutput(OutputStream outStream) throws IOException {
        Writer out = null;
        try {
            Template template = this.config.getTemplate(this.template);
            out = new OutputStreamWriter(outStream);
            template.process(root, out);
            out.flush();
        } catch (TemplateException e) {
            throw new IOException(e.getMessage(), e);
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return out;
    }

    protected void setRootDataModel(String modelId, T model) {
        this.root.clear();
        this.root.put(modelId, model);
    }

    protected Logger getLogger() {
        return this.logger;
    }

}
